package com.design.movieticket.login.filter;

import com.design.movieticket.common.util.JwtUtils;
import com.design.movieticket.login.entity.LoginUser;
import com.design.movieticket.login.service.RedisService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    RedisService redisService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        System.out.println(token);
        if(token == null){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        //token解析
        Claims claims = JwtUtils.verifyJwt(token);
        String id = String.valueOf(claims.get("id"));
        String redisKey = "login" + id;
        log.info("解析得到的redisKey:" + redisKey);

        //从redis中读取信息
        LoginUser loginUser = (LoginUser) redisService.get(redisKey);
        log.info("解析得到的用户:" + loginUser);
        if (loginUser == null){
            throw new RuntimeException("用户未登录");
        }

        //存入SecurityContextHolder,其他filter会通过这个来获取当前用户信息
        //获取权限信息封装到authentication中
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
